import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:web_admin/views/role/role_list_view.dart';
import '../app_config.dart';
import '../../views/auth/login_view.dart';
import '../../views/dashboard/dashboard_view.dart';
import '../../views/product/product_list_view.dart';
import '../../views/order/order_list_view.dart';
import '../../views/user/user_list_view.dart';
import '../../views/organization/organization_list_view.dart';

class AppRouter {
  static final _rootNavigatorKey = GlobalKey<NavigatorState>();
  static final _shellNavigatorKey = GlobalKey<NavigatorState>();

  static final GoRouter router = GoRouter(
    navigatorKey: _rootNavigatorKey,
    initialLocation: '/login',
    redirect: _handleRedirect,
    routes: [
      GoRoute(
        path: '/login',
        builder: (context, state) => const LoginView(),
      ),
      ShellRoute(
        navigatorKey: _shellNavigatorKey,
        builder: (context, state, child) => ScaffoldWithNavigation(child: child),
        routes: [
          GoRoute(
            path: '/dashboard',
            builder: (context, state) => const DashboardView(),
          ),
          GoRoute(
            path: '/products',
            builder: (context, state) => const ProductListView(),
          ),
          GoRoute(
            path: '/orders',
            builder: (context, state) => const OrderListView(),
          ),
          GoRoute(
            path: '/users',
            builder: (context, state) => const UserListView(),
          ),
          GoRoute(
            path: '/organizations',
            builder: (context, state) => const OrganizationListView(),
          ),
          GoRoute(
            path: '/organizations',
            builder: (context, state) => const OrganizationListView(),
          ),
          GoRoute(
            path: '/roles',
            builder: (context, state) => const RoleListView(),
          ),
        ],
      ),
    ],
  );

  static Future<String?> _handleRedirect(BuildContext context, GoRouterState state) async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString(AppConfig.accessTokenKey);
    final isLoginRoute = state.location == '/login';

    if (token == null && !isLoginRoute) {
      return '/login';
    }

    if (token != null && isLoginRoute) {
      return '/dashboard';
    }

    return null;
  }
}

class ScaffoldWithNavigation extends StatelessWidget {
  final Widget child;

  const ScaffoldWithNavigation({Key? key, required this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: [
          NavigationRail(
            extended: true,
            destinations: const [
              NavigationRailDestination(
                icon: Icon(Icons.dashboard),
                label: Text('仪表盘'),
              ),
              NavigationRailDestination(
                icon: Icon(Icons.shopping_bag),
                label: Text('商品管理'),
              ),
              NavigationRailDestination(
                icon: Icon(Icons.receipt),
                label: Text('订单管理'),
              ),
              NavigationRailDestination(
                icon: Icon(Icons.people),
                label: Text('用户管理'),
              ),
              NavigationRailDestination(
                icon: Icon(Icons.business),
                label: Text('机构管理'),
              ),
              NavigationRailDestination(
                icon: Icon(Icons.settings_accessibility_sharp),
                label: Text('角色管理'),
              ),
            ],
            selectedIndex: _calculateSelectedIndex(context),
            onDestinationSelected: (index) => _onItemTapped(index, context),
          ),
          Expanded(child: child),
        ],
      ),
    );
  }

  int _calculateSelectedIndex(BuildContext context) {
    final location = GoRouterState.of(context).location;
    if (location.startsWith('/dashboard')) return 0;
    if (location.startsWith('/products')) return 1;
    if (location.startsWith('/orders')) return 2;
    if (location.startsWith('/users')) return 3;
    if (location.startsWith('/organizations')) return 4;
    if (location.startsWith('/roles')) return 5;
    return 0;
  }

  void _onItemTapped(int index, BuildContext context) {
    switch (index) {
      case 0:
        context.go('/dashboard');
        break;
      case 1:
        context.go('/products');
        break;
      case 2:
        context.go('/orders');
        break;
      case 3:
        context.go('/users');
        break;
      case 4:
        context.go('/organizations');
        break;
      case 5:
        context.go('/roles');
        break;
    }
  }
}